package cn.com.xf.service.impl;

import java.sql.ResultSet;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.com.xf.dao.TblCheckDataDAO;
import cn.com.xf.dao.TblCheckLeaveDAO;
import cn.com.xf.dao.TblCheckMendDAO;
import cn.com.xf.domain.TblCheckData;
import cn.com.xf.service.DataService;
import cn.com.xf.utils.DateUtils;

@Service("dataService")
public class DataServiceImpl implements DataService {

	@Autowired
	private TblCheckDataDAO checkDataDAO;
	
	@Autowired
	private TblCheckLeaveDAO checkLeaveDAO;

	@Autowired
	private TblCheckMendDAO checkMendDAO;
	
	@Override
	public int insertData(TblCheckData data) {
		checkDataDAO.insert(data);
		return 0;
	}

	@Override
	public List<TblCheckData> selectData(int begin, int pageSize,
			String year_Month, String siteid, String deptid, String userid) throws ParseException {
		List<TblCheckData> list = checkDataDAO.select(begin, pageSize, year_Month, siteid, deptid, userid);
		for (int i = 0; i < list.size(); i++) {
			TblCheckData tcd = list.get(i);
			String checkDate = DateUtils.formatDate(tcd.getCheckdate());
			String checkTimes = tcd.getChecktimes();
			List<String> times = getCheckTimes(checkDate, checkTimes);
			String timestr = times.toString().replaceAll("\\[|\\]|\\ ", "");
			tcd.setChecktimes(timestr);
		}
		return list;
	}

	@Override
	public int selectDataCount(String year_Month, String siteid, String deptid, String userid) {
		return checkDataDAO.selectCount(year_Month, siteid, deptid, userid);
	}
	
	@Override
	public int selectDatailReportListCount(String year_Month, String siteid, String deptid) {
		return checkDataDAO.selectDatailReportListCount(year_Month, siteid, deptid);
	}
	@Override
	public List<TblCheckData> selectDatailReportList(int begin, int pageSize,
			String year_Month, String siteid, String deptid) throws ParseException {
		List<TblCheckData> list = checkDataDAO.selectDatailReportList(begin, pageSize, year_Month, siteid, deptid);
		return list;
	}
	

	@Override
	public int deleteData(Long id) {
		return checkDataDAO.deleteByPrimaryKey(id);
	}

	@Override
	public TblCheckData selectDataById(Long id) {
		return checkDataDAO.selectByPrimaryKey(id);
	}

	@Override
	public int insertBatch(List<TblCheckData> list) {
		return checkDataDAO.insertBatch(list);
	}

	@Override
	public List<TblCheckData> selectDataSummary(int begin, int pageSize,
			String userid, String siteid, String deptid, Date startdate,
			Date enddate, String deviceid) {
		return checkDataDAO.selectSummary(begin, pageSize, userid, siteid, deptid, startdate, enddate, deviceid);
	}

	@Override
	public int selectDataSummaryCount(String userid, String siteid,
			String deptid, Date startdate, Date enddate, String deviceid) {
		return checkDataDAO.selectSummaryCount(userid, siteid, deptid, startdate, enddate, deviceid);
	}

	@Override
	public List<TblCheckData> selectUser(String userid, String deviceid,
			Date startdate, Date enddate) {
		return checkDataDAO.selectUser(userid, deviceid, startdate, enddate);
	}



	@Override
	public List<TblCheckData> selectExport(String year_Month, String siteid, String deptid, String userid) throws ParseException {
		List<TblCheckData> useridList = checkDataDAO.selectDistinct(year_Month, siteid, deptid, userid);
		List<TblCheckData> checkList = checkDataDAO.selectExport(year_Month, siteid, deptid, userid);
		List<Date> dateList = getAllDaysOfMonth(year_Month);
		List<TblCheckData> allCDList = new ArrayList<>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		for (TblCheckData tcd : useridList) {
			for (Date days : dateList) {
				TblCheckData allCD = new TblCheckData();
				allCD.setUserid(tcd.getUserid());
				allCD.setUsername(tcd.getUsername());
				allCD.setSiteid(tcd.getSiteid());
				allCD.setSitename(tcd.getSitename());
				allCD.setDeptid(tcd.getDeptid());
				allCD.setDeptname(tcd.getDeptname());
				allCD.setPostname(tcd.getPostname());
				allCD.setCheckdate(days);
				allCD.setWeek(getWeek(days));
				allCDList.add(allCD);
			}
		}
		for (TblCheckData tblCheckData : allCDList) {
			for (TblCheckData checkdata : checkList) {
				if(tblCheckData.getUserid().equals(checkdata.getUserid()) 
						&& tblCheckData.getCheckdate().equals(checkdata.getCheckdate())){
					String checktimes = checkdata.getChecktimes();
					tblCheckData.setChecktimes(checktimes);
					break;
				}
			}			
		}
		return allCDList;
	}
	public static List<String> getCheckTimes(String checkDate ,String checkTimes) throws ParseException{
		Long time30 = 30*60*1000L;
		String [] str = checkTimes.split(",");
		Arrays.sort(str);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		List<String> list = new ArrayList<>();
		for(String t : str){    
			list.add(t); 
		}
		for (int i = list.size() - 1; i >= 1; i--) {
			Long time0 = sdf.parse(checkDate+" "+list.get(i)).getTime();
			Long time1 = sdf.parse(checkDate+" "+list.get(i-1)).getTime();
			if(time0-time1<time30){
				list.remove(i-1);
			}
		}
		return list;
	}
	
	  public static Date getFirstDayOfMonth(Date date) {
	        Calendar calendar = Calendar.getInstance();
	        calendar.setTime(date);
	        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
	        return calendar.getTime();
	    }

	    public static Date getLastDayOfMonth(Date date) {
	        Calendar calendar = Calendar.getInstance();
	        calendar.setTime(date);
	        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
	        return calendar.getTime();
	    }

	    public static Date getNextDay(Date date) {
	        Calendar calendar = Calendar.getInstance();
	        calendar.setTime(date);
	        calendar.add(Calendar.DAY_OF_MONTH, 1);
	        return calendar.getTime();
	    }


	    public static List<Date> getAllDaysOfMonth(String dateStr) throws ParseException {
	    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	        Date date = sdf.parse(dateStr+"-01");
	        List<Date> dateList = new ArrayList<Date>();
	        Date first = getFirstDayOfMonth(date);        
	        Date last = getLastDayOfMonth(date);
	        while (!first.after(last)) {
	            dateList.add(first);
	            first = getNextDay(first);
	        }
	        return dateList;
	    }
	    
	    /**
		 * 
		 * 获取星期
		 */
		public static String getWeek(Date date){		
			String[] weeks = {"日","一","二","三","四","五","六"};
			Calendar cal = Calendar.getInstance();  
	        cal.setTime(date);  
	        int week_index = cal.get(Calendar.DAY_OF_WEEK) - 1;  
	        if(week_index<0){  
	            week_index = 0;  
	        }   
	        return weeks[week_index];
		}

		@Override
		public Map<String, Object> getSitesCheckReport(String siteid, String date) throws Exception {
			String begin = date + " 00:00:01";
			String end = date + " 23:59:59";
			Date begindate = DateUtils.parseDatetimeSecond(begin);
			Date enddate = DateUtils.parseDatetimeSecond(end);
			Map<String, Object> paramMap = new HashMap<>();
			paramMap.put("ASiteID", siteid);
			paramMap.put("AEnterBeginDate", begindate);
			paramMap.put("AEnterEndDate", enddate);
			checkDataDAO.getSitesCheckReport(paramMap);
			return paramMap;
		}

	
}
